<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
        @returnBack="$emit('returnModify')"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :data="formInfo.data"
              :field-list="formInfo.baseInfoFieldList"
              :rules="formInfo.baseInfoRules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
              :image-field="formInfo.imageField"
              @handleEvent="handleEventBaseForm"
            >
              <template v-slot:form-fileUrlList>
                <uploadImg
                  v-model:value="formInfo.data.fileUrlList"
                  multiple
                  :action="formInfo.data.action"
                  :list-type="formInfo.imageField.listType"
                  title="资产图片"
                  :file-type="formInfo.imageField.fileType"
                  :response-fn="handleResponse"
                />
              </template>
              <template v-slot:form-supplierName>
                <el-input
                  type="input"
                  :disabled="true"
                  placeholder="请选择供应商"
                  v-model="formInfo.data.supplierName"
                >
                  <template #append>
                    <el-icon @click="openSupplierWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-deviceTypeValue>
                <el-input
                  v-model="formInfo.data.deviceTypeValue"
                  type="input"
                  :disabled="true"
                  placeholder="请选择医疗器械分类目录"
                >
                  <template #append>
                    <el-icon @click="openDeviceTypeWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-useDeptName>
                <el-input
                  v-model="formInfo.data.useDeptName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openUseDeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-manageDeptName>
                <el-input
                  v-model="formInfo.data.manageDeptName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openManageDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-financialClassifyTypeValue>
                <el-input
                  v-model="formInfo.data.financialClassifyTypeValue"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择资产财务分类"
                >
                  <template #append>
                    <el-icon @click="openFinanceTypeWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-associatedSubcard>
                <!-- //  组件/部件  关联子卡片 -->
                <associatedSubcard
                  ref="associatedSubcardTableForm"
                  :disabeld="true"
                  :assetResourceVOList="formInfo.data.assetResourceVOList"
                />
              </template>
              <template v-slot:form-assetSubcard>
                <!-- //  组件/部件  关联子卡片 -->
                <assetSubcard
                  :id="id"
                  :disabeld="true"
                  ref="assetSubcardTable"
                  :assetSubcardVOList="formInfo.data.relationAsset"
                />
              </template>
              <template v-slot:form-assetCapitalSourceVOList>
                <el-form
                  :model="formInfo"
                  ref="assetCapitalSourceTableForm"
                  style="width: 100%"
                >
                  <page-table
                    v-model:data="formInfo.data.assetCapitalSourceVOList"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :summary="true"
                    :summaryFieldList="
                      assetCapitalSourceTableInfo.summaryFieldList
                    "
                    :field-list="assetCapitalSourceTableInfo.fieldList"
                    :handle="assetCapitalSourceTableInfo.handle"
                  >
                    <template v-slot:col-code="scope">
                      <el-form-item
                        :prop="`data.assetCapitalSourceVOList.${scope.$index}.code`"
                        :rules="[
                          {
                            required: scope.$index >= 0,
                            message: '请选择项目类型',
                            trigger: 'change',
                          },
                        ]"
                      >
                        <select-model
                          v-model.lazy="scope.row.code"
                          width="70%"
                          :type-code="`asset_capital_source`"
                          :clearable="true"
                          @change="changeCapitalSource($event, scope.$index)"
                        />
                      </el-form-item>
                    </template>
                    <template v-slot:col-amount="scope">
                      <el-form-item
                        v-if="scope.$index >= 0"
                        :prop="`data.assetCapitalSourceVOList.${scope.$index}.amount`"
                        :rules="
                          scope.$index >= 0
                            ? [
                                {
                                  validator: $validate.positiveMoneyZeroAsset,
                                  trigger: ['blur', 'change'],
                                },
                              ]
                            : []
                        "
                      >
                        <el-input-number
                          style="width: 70%; display: block"
                          v-model.lazy="scope.row.amount"
                          clearable
                          controls-position="right"
                          :precision="
                            $store.state.permission.systemConfig
                              .assets_price_precision
                          "
                          :min="0"
                          :max="999999999999999"
                          @change="changeAmount"
                        />
                      </el-form-item>
                    </template>
                    <template v-slot:col-capitalProjectList="scope">
                      <el-input
                        v-model="scope.row.capitalProjectName"
                        type="input"
                        :disabled="true"
                        :class="'not-mongolia'"
                        placeholder="请选择资金项目"
                      >
                        <template #append>
                          <el-icon
                            @click="openAssetCapitalProjectList(scope.$index)"
                            ><MoreFilled
                          /></el-icon>
                        </template>
                      </el-input>
                    </template>
                  </page-table>
                </el-form>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('common_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.commonRef"
              :data="formInfo.data"
              :field-list="formInfo.commonInfoFieldList"
              :rules="formInfo.commonRules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-acceptanceUserName>
                <el-input
                  v-model="formInfo.data.acceptanceUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择验收人"
                >
                  <template #append>
                    <el-icon @click="openAcceptanceUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-purchUserName>
                <el-input
                  v-model="formInfo.data.purchUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择采购人"
                >
                  <template #append>
                    <el-icon @click="openPurchUserList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-applicationUserName>
                <el-input
                  v-model="formInfo.data.applicationUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择领用人"
                >
                  <template #append>
                    <el-icon @click="openApplicationUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-receiveUserName>
                <el-input
                  v-model="formInfo.data.receiveUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择接收人"
                >
                  <template #append>
                    <el-icon @click="openReceiveUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-keeperUserName>
                <el-input
                  v-model="formInfo.data.keeperUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择保管人"
                >
                  <template #append>
                    <el-icon @click="openKeeperUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-useUserName>
                <el-input
                  v-model="formInfo.data.useUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择使用人"
                >
                  <template #append>
                    <el-icon @click="openUseUserList"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-responsibleUserName>
                <el-input
                  v-model="formInfo.data.responsibleUserName"
                  type="input"
                  :disabled="true"
                  placeholder="请选择责任人"
                >
                  <template #append>
                    <el-icon @click="openResponsibleUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('finance_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.financeRef"
              :data="formInfo.data"
              :field-list="formInfo.financeInfoFieldList"
              :rules="formInfo.financeInfoRules"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
              @handleEvent="handleEvent"
            >
              <template v-slot:form-postingDate>
                <el-date-picker
                  v-model="formInfo.data.postingDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :disabled-date="productionTimePickerOptions.disabledDate"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-financeDeptName>
                <el-input
                  v-model="formInfo.data.financeDeptName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择部门"
                >
                  <template #append>
                    <el-icon @click="openFinanceDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-assetAmortizationDeptVOList>
                <el-form
                  :model="formInfo"
                  ref="assetAmortizationDeptTableForm"
                  style="width: 93%"
                >
                  <page-table
                    :refresh="assetAmortizationDeptTableInfo.refresh"
                    :init-curpage="assetAmortizationDeptTableInfo.initCurpage"
                    v-model:data="formInfo.data.assetAmortizationDeptVOList"
                    :api="assetAmortizationDeptTableInfo.api"
                    :pager="false"
                    :check-box="false"
                    :tab-index="true"
                    :query="assetAmortizationDeptTableInfo.query"
                    :field-list="assetAmortizationDeptTableInfo.fieldList"
                    :handle="assetAmortizationDeptTableInfo.handle"
                    @handleEvent="handleEvent"
                  >
                    <template v-slot:col-useDeptName="scope">
                      <el-form-item
                        :prop="`data.assetAmortizationDeptVOList.${scope.$index}.useDeptName`"
                        :rules="
                          scope.$index >= 0
                            ? [
                                {
                                  required:
                                    formInfo.data.isFinanceAsset &&
                                    !(
                                      formInfo.data.useStatus == 1 &&
                                      formInfo.data.accrualMark == 1
                                    )
                                      ? true
                                      : false,
                                  message: '请选择使用部门',
                                  trigger: 'change',
                                },
                              ]
                            : []
                        "
                      >
                        <el-input
                          style="width: 100%"
                          v-model="scope.row.useDeptName"
                          type="input"
                          :disabled="true"
                          class="not-mongolia"
                          placeholder="请选择使用部门"
                        >
                          <template #append>
                            <el-icon @click="openAmortizationDept(scope.$index)"
                              ><MoreFilled
                            /></el-icon>
                          </template>
                        </el-input>
                      </el-form-item>
                    </template>
                    <template v-slot:col-rate="scope">
                      <el-form-item
                        v-if="scope.$index >= 0"
                        :prop="`data.assetAmortizationDeptVOList.${scope.$index}.rate`"
                        :rules="
                          scope.$index >= 0
                            ? [
                                {
                                  validator: $validate.positiveScore,
                                  trigger: ['blur', 'change'],
                                },
                              ]
                            : []
                        "
                      >
                        <el-input-number
                          style="width: 100%"
                          v-model.lazy="scope.row.rate"
                          clearable
                          controls-position="right"
                          :precision="2"
                          :min="0"
                          :max="100"
                        />
                      </el-form-item>
                    </template>
                  </page-table>
                </el-form>
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <select-dept
      v-if="selectUseDeptInfo.visible"
      v-model:show-dialog="selectUseDeptInfo.visible"
      :query="selectUseDeptInfo.query"
      :check-box="false"
      :highlight-row="true"
      :saveEmpty="true"
      @callback="selectUseDeptCallback"
    />
    <select-dept
      v-if="selectCommonDeptInfo.visible"
      v-model:show-dialog="selectCommonDeptInfo.visible"
      :query="selectCommonDeptInfo.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectCommonDeptCallback"
    />
    <select-dept
      v-if="selectFinanceDeptInfo.visible"
      v-model:show-dialog="selectFinanceDeptInfo.visible"
      :query="selectFinanceDeptInfo.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectFinanceDeptCallback"
    />

    <select-supplier
      v-if="selectProductSupplier.visible"
      v-model:show-dialog="selectProductSupplier.visible"
      :query="selectProductSupplier.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectProductSupplier.api"
      @callback="selectSupplierCallback"
    />
    <SelectUsers
      v-if="selectKeeperUserInfo.visible"
      v-model:showDialog="selectKeeperUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectKeeperUserCallBack"
    />

    <SelectUsers
      v-if="selectUseUserInfo.visible"
      v-model:showDialog="selectUseUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectUseUserCallBack"
    />

    <SelectUsers
      v-if="selectResponsibleUserInfo.visible"
      v-model:showDialog="selectResponsibleUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectResponsibleUserCallBack"
    />
    <SelectUsers
      v-if="selectAcceptanceUserInfo.visible"
      v-model:showDialog="selectAcceptanceUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAcceptanceUserCallBack"
    />
    <SelectUsers
      v-if="selectPurchUserInfo.visible"
      v-model:showDialog="selectPurchUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectPurchUserCallBack"
    />
    <SelectUsers
      v-if="selectApplicationUserInfo.visible"
      v-model:showDialog="selectApplicationUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectApplicationUserCallBack"
    />
    <SelectUsers
      v-if="selectReceiveUserInfo.visible"
      v-model:showDialog="selectReceiveUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectReceiveUserCallBack"
    />
    <Select-setting-category
      v-if="selectSettingCategoryInfo.visible"
      v-model:showDialog="selectSettingCategoryInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSettingCategoryInfoCallBack"
    />

    <SelectSettingClassification
      v-if="selectSettingClassificationInfo.visible"
      v-model:showDialog="selectSettingClassificationInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSettingClassificationInfoCallBack"
    />
    <select-dept
      v-if="addAssetAmortizationDeptInfo.visible"
      v-model:show-dialog="addAssetAmortizationDeptInfo.visible"
      :query="addAssetAmortizationDeptInfo.query"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAssetAmortizationDeptCallback"
    />
    <SelectAssetCapitalProject
      v-if="selectAssetCapitalProjectInfo.visible"
      v-model:showDialog="selectAssetCapitalProjectInfo.visible"
      :saveEmpty="true"
      :highlight-row="true"
      :query="selectAssetCapitalProjectInfo.query"
      :queryParams="selectAssetCapitalProjectInfo.queryParams"
      :checkedRowList="selectAssetCapitalProjectInfo.checkedRowList"
      @callback="selectAssetCapitalProjectCallBack"
    />
  </div>
</template>

<script setup name="assetfinanceModify">
import {
  getAssetById,
  getSupplierPage,
  financeRegister,
  financeUpdate,
  getUnitAll,
  getCoreCodeStatus,
  financeAdjustAssetCard,
} from '@/api/core'
import utils from '@/common/js/utils' // 公共方法
import { getRrgUserList } from '@/api/base.js'
import { getClassifyDetailsById } from '@/api/asset.js'
import uploadImg from '@/components/UploadImg/index'
import SelectAssetCapitalProject from '@/components/SelectAssetCapitalProject/index'
import associatedSubcard from './component/associatedSubcard.vue'
import assetSubcard from './component/assetSubcard.vue'
import axios from 'axios'
import moment from 'moment'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [String, Number],
  },
  currentAccountingInterval: {
    type: String,
  },

  type: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
})
let validateDeprMonthsLimit = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入折旧月限'))
  } else {
    if (formInfo.value.data.monthsUsed !== '') {
      if (value < formInfo.value.data.monthsUsed) {
        callback(new Error('输入的折旧月限不能小于已使用月数!'))
      } else {
        callback()
      }
    }
    callback()
  }
}
let validateMonthsUsed = (rule, value, callback) => {
  if (value === '' || value == undefined) {
    callback(new Error('请输入已使用月数'))
  } else if (
    formInfo.value.data.deprMonthsLimit < value &&
    formInfo.value.data.deprMethodType != '0'
  ) {
    callback(new Error('输入的已使用月数不能大于折旧月限!'))
  } else {
    const reg = /^(0|[1-9][0-9]*)$/
    if (!reg.test(value) && formInfo.value.data.deprMethodType != '0') {
      callback(new Error('输入大于等于0的整数'))
    } else {
      callback()
    }
  }
}
let validateResidualAmount = (rule, value, callback) => {
  let originalAmount = formInfo.value.data.originalAmount
    ? formInfo.value.data.originalAmount
    : 0
  if (value === '' || value == undefined) {
    callback(new Error('请输入残值'))
  } else if (originalAmount < value) {
    callback(new Error('输入的残值不能大于原值!'))
  } else {
    callback()
  }
}
let validateDeprPreparation = (rule, value, callback) => {
  let originalAmount = formInfo.value.data.originalAmount
    ? formInfo.value.data.originalAmount
    : 0
  if (value === '' || value == undefined) {
    callback()
  } else if (originalAmount < value) {
    callback(new Error('输入的减值准备不能大于原值!'))
  } else {
    callback()
  }
}
let validateSumDeprAmount = (rule, value, callback) => {
  let originalAmount = formInfo.value.data.originalAmount
    ? formInfo.value.data.originalAmount
    : 0
  if (value === '' || value == undefined) {
    callback()
  } else if (originalAmount < value) {
    callback(new Error('输入的累计折旧不能大于原值!'))
  } else {
    callback()
  }
}

const productionTimePickerOptions = ref({})
const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    supplierAuth: 'supplierId',
  },
})
const addAssetAmortizationDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
    idNotIn: '',
  },
})

const selectAcceptanceUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectPurchUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectApplicationUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectReceiveUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectKeeperUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectUseUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectSettingClassificationInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectSettingCategoryInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectResponsibleUserInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectUseDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const selectCommonDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const selectFinanceDeptInfo = ref({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const selectAssetCapitalProjectInfo = ref({
  visible: false,
  saveEmpty: true,
  query: {},
  checkedRowList: [],
  queryParams: {
    assetId: null,
  },
})
const formInfo = ref({
  baseRef: null,
  commonRef: null,
  financeRef: null,
  data: {
    monthsUsed: '',
    residualRate: 0,
    sumDeprAmount: 0,
    deprMonthsLimit: '',
    inputTax: 0,
    residualAmount: 0,
  },
  formDisabled: false,
  delFiledList: [],

  imageField: {
    label: '资产图片',
    value: 'fileUrlList',
    action: axios.defaults.baseURL + '/pub/uploadfile',
    multipleSheets: true,
    listType: 'text',
    limit: 10,
    multiple: false,
    btnDisabled: true,
    fileType: ['png', 'jpg', 'jpeg', 'gif'],
  },
  fieldUploadList: [
    {
      label: '资产图片',
      value: 'fileUrlList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  baseInfoFieldList: [
    {
      label: '资产名称',
      value: 'assetName',
      type: 'input',
      required: true,
      maxlength: 100,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      required: true,
    },
    {
      label: '规格',
      value: 'standard',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '厂家名称',
      value: 'brandName',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '品牌',
      value: 'mark',
      type: 'input',
      maxlength: 100,
    },
    {
      label: '医疗器械分类目录',
      value: 'deviceTypeValue',
      type: 'slot',
    },
    {
      label: '临时采购',
      value: 'temporaryPurch',
      type: 'select-model',
      clearable: true,
      code: 'default_no_or_yes',
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '产地',
      value: 'originPlace',
      type: 'input',
    },

    {
      label: '使用状态',
      value: 'useStatus',
      type: 'select-model',
      code: 'asset_use_status',
    },
    // {
    //   label: '计提标志',
    //   value: 'accrualMark',
    //   type: 'select-model',
    //   clearable: true,
    //   code: 'accrual_mark',
    //   required: true,
    //   disabled: true,
    // },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'slot',
      required: true,
      show: false,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'input',
      show: true,
    },
    {
      label: '管理部门',
      value: 'manageDeptName',
      type: 'slot',
      required: true,
    },
    {
      label: '增加方式',
      value: 'increaseType',
      type: 'select-model',
      // clearable: true,
      code: 'increase_type',
      required: true,
    },
    {
      label: '计量单位',
      value: 'unitId',
      type: 'select',
      clearable: true,
      list: 'unitList',
      required: true,
      filterable: true,
    },
    {
      label: '数量',
      value: 'qty',
      type: 'number',
      max: 99999999,
    },
    {
      label: '金额',
      value: 'primitiveOriginalAmount',
      type: 'number',
      max: 999999999999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      event: 'primitiveOriginalAmount',
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
      type: 'input',
    },
    {
      label: '资产财务分类',
      value: 'financialClassifyTypeValue',
      type: 'slot',
      required: true,
    },
    {
      label: '设备标识',
      value: 'assetMark',
      type: 'select-model',
      clearable: true,
      multiple: true,
      code: 'assets_mark',
    },

    {
      label: '资金来源',
      value: 'assetCapitalSourceVOList',
      type: 'slot',
      className: 'not-br',
      required: true,
    },
    {
      label: '组件/部件',
      value: 'associatedSubcard',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '关联子卡片',
      value: 'assetSubcard',
      type: 'slot',
      className: 'not-br',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  commonInfoFieldList: [
    {
      label: 'SN',
      value: 'machineCode',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '注册证号',
      value: 'registerCode',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '合同号',
      value: 'contractCode',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '档案号',
      value: 'fileCode',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '发票编号',
      value: 'invoiceCode',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '批号',
      value: 'batchNumber',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '出厂日期',
      value: 'manufactureDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '生产日期',
      value: 'productionDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '安装日期',
      value: 'installDate',
      type: 'date',
      placeholder: false,
    },
    // {
    //   label: "启用日期",
    //   value: "enableDate",
    //   type: "date",
    //   placeholder: false,
    // },
    {
      label: '验收人',
      value: 'acceptanceUserName',
      type: 'slot',
    },
    {
      label: '验收日期',
      value: 'acceptanceDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '采购人',
      value: 'purchUserName',
      type: 'slot',
    },
    {
      label: '采购日期',
      value: 'purchDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '开始使用日期',
      value: 'useDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '领用人',
      value: 'applicationUserName',
      type: 'slot',
    },
    {
      label: '领用日期',
      value: 'applicationDate',
      type: 'date',
      placeholder: false,
    },
    {
      label: '保管人',
      value: 'keeperUserName',
      type: 'slot',
    },
    {
      label: '使用人',
      value: 'useUserName',
      type: 'slot',
      required: true,
    },
    {
      label: '责任人',
      value: 'responsibleUserName',
      type: 'slot',
    },

    {
      label: '接收人',
      value: 'receiveUserName',
      type: 'slot',
    },
    {
      label: '存放地点',
      value: 'location',
      type: 'textarea',
      maxlength: 150,
      required: true,
    },
  ],
  financeInfoFieldList: [
    {
      label: '资产类型',
      value: 'assetType',
      type: 'select-model',
      clearable: true,
      code: 'asset_type',
      disabled: true,
    },
    // {
    //   label: '财务部门',
    //   value: 'financeDeptName',
    //   type: 'slot',
    //   required: true,
    // },

    {
      label: '原值',
      value: 'originalAmount',
      type: 'number',
      required: true,
      disabled: true,
      placeholder: false,
      max: 999999999999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
    },
    {
      label: '净值',
      value: 'netAmount',
      type: 'number',
      placeholder: false,
      disabled: true,
      max: 999999999999999,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      labelTip: '计算方法： <br/>' + '原值-累计折旧-减值准备',
    },
    // {
    //   label: '残值',
    //   value: 'residualAmount',
    //   type: 'number',
    //   required: true,
    //   placeholder: false,
    //   formatter: proxy.$fn.TripartiteMethodAsset,
    //   precision:
    //     proxy.$store.state.permission.systemConfig.assets_price_precision,
    //   max: 999999999999999,
    //   event: 'residualAmount',
    // },
    // {
    //   label: '残值率(%)',
    //   value: 'residualRate',
    //   type: 'number',
    //   required: true,
    //   placeholder: false,
    //   formatter: proxy.$fn.TripartiteMethodAsset,
    //   precision:
    //     proxy.$store.state.permission.systemConfig.assets_price_precision,
    //   max: 100,
    //   event: 'residualRate',
    // },
    {
      label: '折旧月限',
      value: 'deprMonthsLimit',
      type: 'number',
      required: true,
      placeholder: false,
      max: 99999999,
    },
    {
      label: '已使用月数',
      value: 'monthsUsed',
      type: 'number',
      // required: true,
      placeholder: false,
      max: 99999999,
    },
    {
      label: '减值准备',
      value: 'deprPreparation',
      type: 'number',
      placeholder: false,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      max: 999999999999999,
    },
    {
      label: '累计折旧',
      value: 'sumDeprAmount',
      type: 'number',
      required: true,
      placeholder: false,
      formatter: proxy.$fn.TripartiteMethodAsset,
      precision:
        proxy.$store.state.permission.systemConfig.assets_price_precision,
      max: 999999999999999,
    },
    {
      label: '折旧方法',
      value: 'deprMethodType',
      type: 'select-model',
      clearable: true,
      code: 'depr_method_type',
      required: true,
    },
    {
      label: '折旧惯例',
      value: 'deprConvention',
      type: 'select-model',
      clearable: true,
      code: 'depr_convention',
      required: true,
      // disabled: true,
    },
    // {
    //   label: '进项税',
    //   value: 'inputTax',
    //   type: 'number',
    //   placeholder: false,
    //   formatter: proxy.$fn.TripartiteMethodAsset,
    //   precision:
    //     proxy.$store.state.permission.systemConfig.assets_price_precision,
    //   max: 999999999999999,
    // },
    {
      label: '入账日期',
      value: 'postingDate',
      type: 'slot',
    },
    // {
    //   label: '月折旧率(%)',
    //   value: 'monthDeprRate',
    //   type: 'number',
    //   formatter: proxy.$fn.TripartiteMethodAsset,
    //   disabled: true,
    //   precision:
    //     proxy.$store.state.permission.systemConfig.assets_price_precision,
    //   max: 100,
    //   labelTip: '平均折旧法 <br/>' + '月折旧率(%)： 1/折旧月限*100<br/>',
    // },
    // {
    //   label: '月折旧额',
    //   value: 'monthDeprAmount',
    //   type: 'number',
    //   formatter: proxy.$fn.TripartiteMethodAsset,
    //   disabled: true,
    //   precision:
    //     proxy.$store.state.permission.systemConfig.assets_price_precision,
    //   max: 999999999999999,
    //   labelTip: '平均折旧法 <br/>' + '月折旧额： (原值-减值准备)*月折旧率<br/>',
    // },
    {
      label: '使用部门',
      value: 'assetAmortizationDeptVOList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  baseInfoRules: {
    financialClassifyTypeValue: [
      {
        required: true,
        message: '请选择资产财务分类',
        trigger: 'change',
      },
    ],
    assetCapitalSourceVOList: [
      {
        required: true,
        // message: "请选择资产财务分类",
        // trigger: "change",
      },
    ],
  },
  commonRules: {},
  financeInfoRules: {
    financeTypeValue: [
      {
        required: true,
        message: '请选择财务资产分类',
        trigger: 'blur',
      },
    ],

    // accrualMark: [
    //   {
    //     required: true,
    //     message: '请选择计提标志',
    //     trigger: 'change',
    //   },
    // ],
    originalAmount: [
      {
        required: true,
        message: '请输入原值',
        trigger: 'blur',
      },
      {
        validator: proxy.$validate.positiveAssetMoneyZero,
        trigger: 'blur',
      },
    ],
    // residualAmount: [
    //   {
    //     required: true,
    //     validator: validateResidualAmount,
    //     trigger: 'blur',
    //   },
    //   {
    //     validator: proxy.$validate.positiveAssetMoneyZero,
    //     trigger: 'blur',
    //   },
    // ],
    deprMonthsLimit: [
      {
        required: true,
        validator: validateDeprMonthsLimit,
        trigger: 'blur',
      },
      {
        validator: proxy.$validate.positiveAssetMoneyZero,
        trigger: 'blur',
      },
    ],
    deprPreparation: [
      {
        validator: validateDeprPreparation,
        trigger: 'blur',
      },
    ],
    // residualRate: [
    //   {
    //     required: true,
    //     message: '请输入残值率',
    //     trigger: 'blur',
    //   },
    //   {
    //     validator: proxy.$validate.positiveAssetMoneyZero,
    //     trigger: 'blur',
    //   },
    // ],
    monthsUsed: [
      {
        required: true,
        validator: validateMonthsUsed,
        trigger: 'blur',
      },
    ],
    sumDeprAmount: [
      {
        required: true,
        validator: validateSumDeprAmount,
        trigger: 'blur',
      },
      {
        validator: proxy.$validate.positiveAssetMoneyZero,
        trigger: 'blur',
      },
    ],
    deprMethodType: [
      {
        required: true,
        message: '请选择折旧方法',
        trigger: 'blur',
      },
    ],
    deprConvention: [
      {
        required: true,
        message: '请选择折旧惯例',
        trigger: 'blur',
      },
    ],
    postingDate: [
      {
        required: true,
        message: '请输入入账日期',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const listTypeInfo = ref({
  licenseList: [],
  brandList: [],
  unitList: [],
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
//资金来源表格
const assetCapitalSourceTableInfo = ref({
  data: [],
  summaryFieldList: [
    { value: 'amount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    {
      label: '项目类型',
      value: 'code',
      type: 'slot',
    },
    {
      label: '金额',
      value: 'amount',
      type: 'slot',
    },
    {
      label: '资金项目',
      value: 'capitalProjectList',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: addSource,
        show: true,
      },
      {
        label: '删除',
        event: removeSource,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderRemoveSource,
      },
    ],
  },
})
//使用部门表格
const assetAmortizationDeptTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: null,

  fieldList: [
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'slot',
    },
    {
      label: '占比(%)',
      value: 'rate',
      type: 'slot',
      labelTip: '总值100%',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '新增行',
        event: addDept,
        show: true,
      },
      {
        label: '清空',
        event: clearDept,
        popconfirmText: '清空后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderClearDept,
      },
      {
        label: '删除',
        event: removeDept,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
        ifRender: ifRenderRemoveDept,
      },
    ],
  },
})
const flag = ref(true)
const addAssetAmortizationDeptIndex = ref(null)
const changeAmountFlag = ref(false)
const changeuseDeptNameFlag = ref(false)
const assetAmortizationDeptTableForm = ref()
const assetCapitalSourceTableForm = ref()
const formRefs = ref(null)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})

watch(
  //初始原值
  () => formInfo.value.data.primitiveOriginalAmount,
  (value) => {
    formInfo.value.data.originalAmount = value
    formInfo.value.data.netAmount = utils.Subtr(
      utils.Subtr(
        utils.Subtr(
          formInfo.value.data.originalAmount || 0,
          formInfo.value.data.residualAmount || 0
        ),
        formInfo.value.data.sumDeprAmount || 0
      ),
      formInfo.value.data.deprPreparation || 0
    )
  }
)

watch(
  //原值
  () => formInfo.value.data.originalAmount,
  (value) => {
    if (flag.value) {
      // let residualRate = formInfo.value.data.residualRate
      //   ? formInfo.value.data.residualRate
      //   : 0
      // if (residualRate) {
      //   formInfo.value.data.residualAmount =
      //     utils.accMul(formInfo.value.data.residualRate, value) / 100
      // }
      let residualAmount = formInfo.value.data.residualAmount
        ? formInfo.value.data.residualAmount
        : 0
      let sumDeprAmount = formInfo.value.data.sumDeprAmount
        ? formInfo.value.data.sumDeprAmount
        : 0
      let deprPreparation = formInfo.value.data.deprPreparation
        ? formInfo.value.data.deprPreparation
        : 0
      let netAmount = utils.Subtr(
        utils.Subtr(utils.Subtr(value, residualAmount), sumDeprAmount),
        deprPreparation
      )
      formInfo.value.data.netAmount = netAmount
      changeMouthDepr()
    }
  }
)

watch(
  //折旧方法
  () => formInfo.value.data.deprMethodType,
  (value) => {
    if (flag.value) {
      changeMouthDepr()
    }
    if (value == '0') {
      //如果不折旧，那么隐藏所有跟折旧有关的值，并置为0
      showFinanceFieldListItem(false, 'deprMonthsLimit')
      // showFinanceFieldListItem(false, 'residualAmount')
      // showFinanceFieldListItem(false, 'residualRate')
      showFinanceFieldListItem(false, 'deprPreparation')
      showFinanceFieldListItem(false, 'sumDeprAmount')
      showFinanceFieldListItem(false, 'deprConvention')
      showFinanceFieldListItem(false, 'monthDeprRate')
      showFinanceFieldListItem(false, 'monthDeprAmount')

      formInfo.value.data.deprPreparation = 0
      formInfo.value.data.deprMonthsLimit = 0
      // formInfo.value.data.residualAmount = 0
      // formInfo.value.data.residualRate = 0
      formInfo.value.data.sumDeprAmount = 0
      formInfo.value.data.deprConvention = 0
    } else {
      showFinanceFieldListItem(true, 'deprMonthsLimit')
      // showFinanceFieldListItem(true, 'residualAmount')
      // showFinanceFieldListItem(true, 'residualRate')
      showFinanceFieldListItem(true, 'deprPreparation')
      showFinanceFieldListItem(true, 'sumDeprAmount')
      showFinanceFieldListItem(true, 'deprConvention')
      showFinanceFieldListItem(true, 'monthDeprRate')
      showFinanceFieldListItem(true, 'monthDeprAmount')
    }
  }
)

watch(
  //减值准备
  () => formInfo.value.data.deprPreparation,
  (value) => {
    if (flag.value) {
      let originalAmount = formInfo.value.data.originalAmount
        ? formInfo.value.data.originalAmount
        : 0
      let sumDeprAmount = formInfo.value.data.sumDeprAmount
        ? formInfo.value.data.sumDeprAmount
        : 0
      let residualAmount = formInfo.value.data.residualAmount
        ? formInfo.value.data.residualAmount
        : 0
      let netAmount = utils.Subtr(
        utils.Subtr(utils.Subtr(originalAmount, residualAmount), sumDeprAmount),
        value
      )
      formInfo.value.data.netAmount = netAmount
      changeMouthDepr()
    }
  }
)
watch(
  //累计折旧
  () => formInfo.value.data.sumDeprAmount,
  () => {
    if (flag.value) {
      let originalAmount = formInfo.value.data.originalAmount
        ? formInfo.value.data.originalAmount
        : 0
      let sumDeprAmount = formInfo.value.data.sumDeprAmount
        ? formInfo.value.data.sumDeprAmount
        : 0
      let residualAmount = formInfo.value.data.residualAmount
        ? formInfo.value.data.residualAmount
        : 0
      let deprPreparation = formInfo.value.data.deprPreparation
        ? formInfo.value.data.deprPreparation
        : 0
      let netAmount = utils.Subtr(
        utils.Subtr(utils.Subtr(originalAmount, residualAmount), sumDeprAmount),
        deprPreparation
      )
      formInfo.value.data.netAmount = netAmount
    }
  }
)
watch(
  //折旧月限
  () => formInfo.value.data.deprMonthsLimit,
  () => {
    if (flag.value) {
      changeMouthDepr()
    }
  }
)

watch(
  //监听一个必有的字段，确保初始化之后flag为true
  () => formInfo.value.data.assetName,
  () => {
    flag.value = true
  }
)
onMounted(() => {
  getUnitList()
  let currentAccountingInterval = props.currentAccountingInterval
  productionTimePickerOptions.value = {
    disabledDate(time) {
      if (currentAccountingInterval) {
        return (
          time.getTime() <
          new Date(currentAccountingInterval).getTime() - 24 * 60 * 60 * 1000
        )
      }
    },
  }
  if (props.id) {
    formInfo.value.baseInfoFieldList.forEach((item) => {
      if (item.value !== 'primitiveOriginalAmount') {
        item.disabled = true
      }
    })
    formInfo.value.commonInfoFieldList.forEach((item) => {
      item.disabled = true
    })
    getDetails()
    flag.value = false
  }
})
function openAssetCapitalProjectList(index) {
  //打开资金项目弹窗
  selectAssetCapitalProjectInfo.value.index = index
  let assetCapitalSourceVOListElement =
    formInfo.value.data.assetCapitalSourceVOList[index]
  if (
    assetCapitalSourceVOListElement.capitalProjectList &&
    assetCapitalSourceVOListElement.capitalProjectList.length
  ) {
    selectAssetCapitalProjectInfo.value.checkedRowList =
      assetCapitalSourceVOListElement.capitalProjectList
  } else {
    selectAssetCapitalProjectInfo.value.checkedRowList = []
  }
  // selectAssetCapitalProjectInfo.value.query['assetCapitalSourceDictId'] = {
  //   queryType: 'EQUALS',
  //   value: assetCapitalSourceVOListElement.code,
  // }
  if (props.id) {
    selectAssetCapitalProjectInfo.value.queryParams.assetId = props.id
  }
  selectAssetCapitalProjectInfo.value.visible = true
}
function selectAssetCapitalProjectCallBack(data, arr) {
  //资金项目
  if (data && data.length) {
    let capitalProjectName = data.map((item) => item.name).toString()
    console.log(data)
    formInfo.value.data.assetCapitalSourceVOList[
      selectAssetCapitalProjectInfo.value.index
    ].capitalProjectName = capitalProjectName

    formInfo.value.data.assetCapitalSourceVOList[
      selectAssetCapitalProjectInfo.value.index
    ].capitalProjectList = data.map((item) => {
      return {
        assetCapitalProjectId: item.id,
        useAmount: item.useAmount,
      }
    })

    formInfo.value.data.assetCapitalSourceVOList[
      selectAssetCapitalProjectInfo.value.index
    ].capitalProjectList.forEach((item) => {
      arr.forEach((el) => {
        if (el.id === item.id) {
          item.useAmount = el.useAmount
        }
      })
    })
  } else {
    formInfo.value.data.assetCapitalSourceVOList[
      selectAssetCapitalProjectInfo.value.index
    ].capitalProjectName = ''

    formInfo.value.data.assetCapitalSourceVOList[
      selectAssetCapitalProjectInfo.value.index
    ].capitalProjectList = []
  }
}
function changeCapitalSource(val, index) {
  formInfo.value.data.assetCapitalSourceVOList[index].capitalProjectList = []
}
function ifRenderRemoveSource() {
  if (formInfo.value.data.assetCapitalSourceVOList.length - 1) {
    return true
  } else {
    return false
  }
}
function addSource() {
  //增加资金来源
  formInfo.value.data.assetCapitalSourceVOList.push({
    code: '',
    amount: 0,
  })
}
function removeSource(row) {
  //删除资金来源
  formInfo.value.data.assetCapitalSourceVOList =
    formInfo.value.data.assetCapitalSourceVOList.filter((item) => item !== row)
  changeAmount()
}
function changeAmount() {
  changeAmountFlag.value = true
  let primitiveOriginalAmount = 0
  if (
    formInfo.value.data.assetCapitalSourceVOList &&
    formInfo.value.data.assetCapitalSourceVOList.length
  ) {
    formInfo.value.data.assetCapitalSourceVOList.forEach((item) => {
      primitiveOriginalAmount = proxy.$fn.accAdd(
        item.amount || 0,
        primitiveOriginalAmount
      )
    })
  }
  formInfo.value.data.primitiveOriginalAmount = primitiveOriginalAmount
}
function handleEventBaseForm(event) {
  if (event === 'primitiveOriginalAmount') {
    if (
      !changeAmountFlag.value &&
      formInfo.value.data.assetCapitalSourceVOList &&
      formInfo.value.data.assetCapitalSourceVOList.length === 1
    ) {
      formInfo.value.data.assetCapitalSourceVOList[
        formInfo.value.data.assetCapitalSourceVOList.length - 1
      ].amount = formInfo.value.data.primitiveOriginalAmount
    }
  }
}
function openAmortizationDept(index) {
  //新增使用部门
  let ids = []
  if (
    formInfo.value.data.assetAmortizationDeptVOList &&
    formInfo.value.data.assetAmortizationDeptVOList.length
  ) {
    formInfo.value.data.assetAmortizationDeptVOList.forEach((item) => {
      if (item.useDeptName) {
        ids.push(item.useDeptId)
      }
    })
  }
  addAssetAmortizationDeptInfo.value.query.idNotIn = String(ids)
  addAssetAmortizationDeptIndex.value = index
  addAssetAmortizationDeptInfo.value.visible = true
}
function addDept() {
  formInfo.value.data.assetAmortizationDeptVOList.unshift({
    useDeptName: '',
  })
  proxy.$nextTick(() => {
    assetAmortizationDeptTableForm.value.clearValidate()
  })
}
function selectAssetAmortizationDeptCallback(data) {
  if (data) {
    formInfo.value.data.assetAmortizationDeptVOList.forEach((item, index) => {
      if (index === addAssetAmortizationDeptIndex.value) {
        item.useDeptName = data.name
        item.useDeptId = data.id
      }
    })
  } else {
    formInfo.value.data.assetAmortizationDeptVOList.forEach((item, index) => {
      if (index === addAssetAmortizationDeptIndex.value) {
        item.useDeptName = ''
        item.useDeptId = -2
      }
    })
  }
  addAssetAmortizationDeptInfo.value.visible = false
}
function removeDept(row) {
  //删除使用部门
  formInfo.value.data.assetAmortizationDeptVOList =
    formInfo.value.data.assetAmortizationDeptVOList.filter(
      (item) => item !== row
    )
}
function ifRenderRemoveDept() {
  if (formInfo.value.data.assetAmortizationDeptVOList.length - 1) {
    return true
  } else {
    return false
  }
}
function clearDept() {
  //清空使用部门
  formInfo.value.data.assetAmortizationDeptVOList = [
    { useDeptName: '' },
  ]
}
function ifRenderClearDept() {
  if (formInfo.value.data.assetAmortizationDeptVOList.length === 1) {
    return true
  } else {
    return false
  }
}
function handleResponse(response) {
  return response
}
function handleEvent(e) {
  // if (e === 'residualAmount') {
  //   let residualRate =
  //     utils.accDiv(
  //       formInfo.value.data.residualAmount,
  //       formInfo.value.data.originalAmount
  //     ) * 100
  //   formInfo.value.data.residualRate = residualRate
  // } else if (e === 'residualRate') {
  //   let residualAmount =
  //     utils.accMul(
  //       formInfo.value.data.residualRate,
  //       formInfo.value.data.originalAmount
  //     ) / 100
  //   formInfo.value.data.residualAmount = residualAmount
  // }
}
function changeMouthDepr() {
  let value = formInfo.value.data.deprMethodType

  let deprMonthsLimit = formInfo.value.data.deprMonthsLimit
    ? formInfo.value.data.deprMonthsLimit
    : 0
  let originalAmount = formInfo.value.data.originalAmount
    ? formInfo.value.data.originalAmount
    : 0
  let deprPreparation = formInfo.value.data.deprPreparation
    ? formInfo.value.data.deprPreparation
    : 0

  if (value == '0') {
    //不折旧
    formInfo.value.data.monthDeprRate = 0
    formInfo.value.data.monthDeprAmount = 0
  } else if (value == '1') {
    //平均折旧法
    let residualRate = 0
    if (deprMonthsLimit) {
      let monthDeprRate = utils.accDiv(
        utils.Subtr(1, residualRate),
        deprMonthsLimit
      )
      let monthDeprAmount

      monthDeprAmount = utils.accMul(
        utils.Subtr(originalAmount || 0, deprPreparation || 0),
        utils.getAssetRate(monthDeprRate)
      )

      formInfo.value.data.monthDeprRate = monthDeprRate * 100
      formInfo.value.data.monthDeprAmount = monthDeprAmount
    } else {
      formInfo.value.data.monthDeprRate = 0
      formInfo.value.data.monthDeprAmount = 0
    }
  }
}

function openUseDeptWindow() {
  //selectUseDeptInfo.value.visible = true;
}
function openManageDeptWindow() {
  //selectCommonDeptInfo.value.visible = true;
}
function openFinanceDeptWindow() {
  selectFinanceDeptInfo.value.visible = true
}
function openSupplierWindow() {
  //selectProductSupplier.value.visible = true;
}

function openAcceptanceUserList() {
  //selectAcceptanceUserInfo.value.visible = true;
}
function openPurchUserList() {
  //selectPurchUserInfo.value.visible = true;
}
function openApplicationUserList() {
  //selectApplicationUserInfo.visible = true;
}
function openReceiveUserList() {
  //selectReceiveUserInfo.value.visible = true;
}
function openKeeperUserList() {
  //selectKeeperUserInfo.value.visible = true;
}
function openUseUserList() {
  //selectUseUserInfo.value.visible = true;
}
function openResponsibleUserList() {
  //selectResponsibleUserInfo.value.visible = true;
}
function openFinanceTypeWindow() {
  selectSettingCategoryInfo.value.visible = true
}
function openDeviceTypeWindow() {
  //selectSettingClassificationInfo.value.visible = true;
}

function selectUseDeptCallback(row) {
  if (row) {
    formInfo.value.data.useDeptId = row.id
    formInfo.value.data.useDeptName = row.name
  } else {
    formInfo.value.data.useDeptId = '.'
    formInfo.value.data.useDeptName = ''
  }
  if (
    formInfo.value.data.assetAmortizationDeptVOList.length &&
    !changeuseDeptNameFlag.value
  ) {
    formInfo.value.data.assetAmortizationDeptVOList[
      formInfo.value.data.assetAmortizationDeptVOList.length - 1
    ].useDeptName = formInfo.value.data.useDeptName

    formInfo.value.data.assetAmortizationDeptVOList[
      formInfo.value.data.assetAmortizationDeptVOList.length - 1
    ].useDeptId = formInfo.value.data.useDeptId

    formInfo.value.data.assetAmortizationDeptVOList[
      formInfo.value.data.assetAmortizationDeptVOList.length - 1
    ].rate = 100
  }
}
function selectCommonDeptCallback(row) {
  if (row) {
    formInfo.value.data.manageDeptId = row.id
    formInfo.value.data.manageDeptName = row.name
  } else {
    formInfo.value.data.manageDeptId = ''
    formInfo.value.data.manageDeptName = ''
  }
}
function selectFinanceDeptCallback(row) {
  if (row) {
    formInfo.value.data.financeDeptId = row.id
    formInfo.value.data.financeDeptName = row.name
  } else {
    formInfo.value.data.financeDeptId = ''
    formInfo.value.data.financeDeptName = ''
  }
}
function selectSupplierCallback(row) {
  if (row) {
    formInfo.value.data.supplierId = row.supplierId
    formInfo.value.data.supplierName = row.supplierName
  } else {
    formInfo.value.data.supplierId = ''
    formInfo.value.data.supplierName = ''
  }
}

function selectKeeperUserCallBack(row) {
  if (row) {
    formInfo.value.data.keeperUser = row.id
    formInfo.value.data.keeperUserName = row.name
  } else {
    formInfo.value.data.keeperUser = ''
    formInfo.value.data.keeperUserName = ''
  }
}
function selectUseUserCallBack(row) {
  if (row) {
    formInfo.value.data.useUser = row.id
    formInfo.value.data.useUserName = row.name
  } else {
    formInfo.value.data.useUser = ''
    formInfo.value.data.useUserName = ''
  }
}
function selectResponsibleUserCallBack(row) {
  if (row) {
    formInfo.value.data.responsibleUser = row.id
    formInfo.value.data.responsibleUserName = row.name
  } else {
    formInfo.value.data.responsibleUser = ''
    formInfo.value.data.responsibleUserName = ''
  }
}
function selectSettingCategoryInfoCallBack(row) {
  if (row) {
    formInfo.value.data.financialClassifyType = row.id
    formInfo.value.data.financialClassifyTypeValue = row.name
    // formInfo.value.data, "financeType", row.id);
    // formInfo.value.data, "financeTypeValue", row.name);
    // formInfo.value.data, "assetType", row.assetType);
    // formInfo.value.data, "assetTypeValue", row.assetTypeValue);
    formInfo.value.data.deprConvention = row.deprConvention
    formInfo.value.data.deprConventionValue = row.deprConventionValue
    formInfo.value.data.deprMethodType = row.deprMethodType
    formInfo.value.data.deprMethodTypeValue = row.deprMethodTypeValue
    formInfo.value.data.deprMonthsLimit = row.deprMonthsLimit
    // formInfo.value.data.residualRate = row.residualRate
  } else {
    formInfo.value.data.financialClassifyType = ''
    formInfo.value.data.financialClassifyTypeValue = ''

    formInfo.value.data.deprConvention = ''
    formInfo.value.data.deprConventionValue = ''
    formInfo.value.data.deprMethodType = ''
    formInfo.value.data.deprMethodTypeValue = ''
    formInfo.value.data.deprMonthsLimit = ''
    // formInfo.value.data.residualRate = ''
  }
}

function selectSettingClassificationInfoCallBack(row) {
  if (row) {
    formInfo.value.data.deviceType = row.id
    formInfo.value.data.deviceTypeValue = row.name
  } else {
    formInfo.value.data.deviceType = ''
    formInfo.value.data.deviceTypeValue = ''
  }
}
function selectAcceptanceUserCallBack(row) {
  if (row) {
    formInfo.value.data.acceptanceUser = row.id
    formInfo.value.data.acceptanceUserName = row.name
  } else {
    formInfo.value.data.acceptanceUser = ''
    formInfo.value.data.acceptanceUserName = ''
  }
}
function selectPurchUserCallBack(row) {
  if (row) {
    formInfo.value.data.purchUser = row.id
    formInfo.value.data.purchUserName = row.name
  } else {
    formInfo.value.data.purchUser = ''
    formInfo.value.data.purchUserName = ''
  }
}
function selectApplicationUserCallBack(row) {
  if (row) {
    formInfo.value.data.applicationUser = row.id
    formInfo.value.data.applicationUserName = row.name
  } else {
    formInfo.value.data.applicationUser = ''
    formInfo.value.data.applicationUserName = ''
  }
}
function selectReceiveUserCallBack(row) {
  if (row) {
    formInfo.value.data.receiveUser = row.id
    formInfo.value.data.receiveUserName = row.name
  } else {
    formInfo.value.data.receiveUser = ''
    formInfo.value.data.receiveUserName = ''
  }
}

//获取计量单位列表
function getUnitList() {
  getUnitAll().then((resp) => {
    if (resp && resp.success && resp.data && resp.data.length > 0) {
      listTypeInfo.value.unitList = resp.data.map(function (item) {
        return { key: item.name, value: item.id }
      })
    }
  })
}
function getStatus() {
  getCoreCodeStatus({ codeType: '7' }).then((res) => {
    showFieldListItem(!res.data, 'assetCode')
  })
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.baseInfoFieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function save() {
  if (formInfo.value.data.assetCapitalSourceVOList.length) {
    //资金来源：一份资产卡片只能拥有一行相同的项目类型
    let warning = false
    formInfo.value.data.assetCapitalSourceVOList.some((e, index, arr) => {
      if (arr.filter((e1) => e1.code == e.code).length > 1) {
        warning = true
      }
    })
    if (warning) {
      proxy.$message.warning('一份资产卡片只能拥有一行相同的项目类型')
      return
    }
    let primitiveOriginalAmount = 0
    formInfo.value.data.assetCapitalSourceVOList.forEach((item) => {
      primitiveOriginalAmount = proxy.$fn.accAdd(
        item.amount || 0,
        primitiveOriginalAmount || 0
      )
    })
    if (
      primitiveOriginalAmount !== formInfo.value.data.primitiveOriginalAmount
    ) {
      proxy.$message.warning('项目类型金额合计要与金额相等！')
      return
    }
    let _warning = false
    let _warningIndex = []
    formInfo.value.data.assetCapitalSourceVOList.forEach((item, index) => {
      let useAmount = 0
      if (item.capitalProjectList && item.capitalProjectList.length) {
        item.capitalProjectList.forEach((el) => {
          useAmount = proxy.$fn.accAdd(el.useAmount || 0, useAmount)
        })
        if (useAmount > item.amount) {
          _warning = true
          _warningIndex.push(index + 1)
        }
      }
    })
    if (_warning) {
      proxy.$message.warning(
        `【第${String(
          _warningIndex
        )}行】的资金项目使用金额之和不能大于资金来源金额！`
      )
      return
    }
  }
  if (
    formInfo.value.data.assetAmortizationDeptVOList.length > 0 &&
    formInfo.value.data.isFinanceAsset
  ) {
    //使用部门
    let rate = 0
    let assetAmortizationDeptVOList =
      formInfo.value.data.assetAmortizationDeptVOList.filter((item) => {
        rate = proxy.$fn.accAdd(
          rate,
          item.rate || 0
        )
        return !!item.useDeptName
      })
    if (rate !== 100 && assetAmortizationDeptVOList.length) {
      proxy.$message.warning('使用部门的占比总值必须为100%!')
      return
    }
  }
  formRefs.value = [
    formInfo.value.baseRef,
    formInfo.value.commonRef,
    formInfo.value.financeRef,
    assetCapitalSourceTableForm.value,
    // assetAmortizationDeptTableForm.value,
  ]
  if (
    formInfo.value.data.isFinanceAsset &&
    assetAmortizationDeptTableForm.value &&
    !(
      formInfo.value.data.useStatus == 1
    )
  ) {
    //使用部门的校验
    //资产卡片使用状态为【带领用】，计提标志为【不计提】折旧时，使用部门可不填
    formRefs.value.push(assetAmortizationDeptTableForm.value)
  }

  if (!props.currentAccountingInterval) {
    proxy.$message({
      type: 'error',
      duration: 3500,
      message: '未开启会计期间，请先开启会计期间!',
      showClose: true,
    })
  } else {
    proxy.$fn
      .checkForm(formRefs.value)
      .then(() => {
        //折旧月限和已使用月数相同，净值必须为0，否则不允许折旧月限和已使用月数相同。
        if (
          formInfo.value.data.deprMonthsLimit ===
            formInfo.value.data.monthsUsed &&
          formInfo.value.data.netAmount !== 0 &&
          formInfo.value.data.deprMethodType != '0'
        ) {
          proxy.$message({
            type: 'warning',
            duration: 3500,
            message: '折旧月限和已使用月数相同，净值必须为0',
            showClose: true,
          })
          return
        }
        formInfo.value.data.billFilePath = formInfo.value.data.fileUrlList
          ? formInfo.value.data.fileUrlList.join(',')
          : ''
        const params = {
          ...formInfo.value.data,
        }
        if (
          !(
            params.assetAmortizationDeptVOList.length &&
            params.assetAmortizationDeptVOList[0].useDeptName
          )
        ) {
          delete params.assetAmortizationDeptVOList
        }
        if (props.type === 'financeRegister' || props.type === 'create') {
          financeRegister(params).then((res) => {
            if (res.success) {
              showDialog.value = false
              emits('returnModify', false)
            }
          })
        } else if (props.type === 'update') {
          financeUpdate(params).then((res) => {
            if (res.success) {
              showDialog.value = false
              emits('returnModify', false)
            }
          })
        } else if (props.type === 'financeAdjust') {
          financeAdjustAssetCard(params).then((res) => {
            if (res.success) {
              showDialog.value = false
              emits('returnModify', false)
            }
          })
        }
      })
      .catch(() => {
        proxy.$message({
          message: '必填或非法校验未通过，请检查！',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
      })
  }
}

function showFinanceFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.financeInfoFieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

function getDetails() {
  getAssetById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      let data = resp.data
      if (
        data.assetCapitalSourceVOList &&
        data.assetCapitalSourceVOList.length
      ) {
        data.assetCapitalSourceVOList.forEach((item) => {
          if (item.capitalProjectList && item.capitalProjectList.length) {
            item.capitalProjectName = item.capitalProjectList
              .map((el) => el.assetCapitalProjectName)
              .toString()
          }
          return item
        })
      }
      formInfo.value.data = {
        ...formInfo.value.data,
        isFinanceAsset: 1,
        unitId: data.unitId === -2 ? '' : data.unitId,
        assetType: data.assetType === -2 ? '' : data.assetType,
        deviceType: data.deviceType === -2 ? '' : data.deviceType,
        financeType: data.financeType === -2 ? '' : data.financeType,
        assetAmortizationDeptVOList:
          data.assetAmortizationDeptVOList &&
          data.assetAmortizationDeptVOList.length
            ? data.assetAmortizationDeptVOList
            : [{ useDeptName: '' }],
        assetCapitalSourceVOList:
          data.assetCapitalSourceVOList && data.assetCapitalSourceVOList.length
            ? data.assetCapitalSourceVOList
            : [{ code: '', amount: data.primitiveOriginalAmount }],
        netAmount:
          data.netAmount ||
          utils.Subtr(
            utils.Subtr(
              utils.Subtr(data.originalAmount || 0, data.residualAmount || 0),
              data.sumDeprAmount || 0
            ),
            data.deprPreparation || 0
          ),
        postingDate: moment(new Date()).format('YYYY-MM-DD'),
      }
      formInfo.value.data.fileUrlList = resp.data.fileUrlList || []
      let assetAmortizationDeptVOList =
        formInfo.value.data.assetAmortizationDeptVOList.filter(
          (item) => !!item.useDeptName
        )
      if (
        !assetAmortizationDeptVOList.length &&
        !changeuseDeptNameFlag.value &&
        Number(formInfo.value.data.useStatus) === 2
      ) {
        formInfo.value.data.assetAmortizationDeptVOList[
          formInfo.value.data.assetAmortizationDeptVOList.length - 1
        ].useDeptName = formInfo.value.data.useDeptName

        formInfo.value.data.assetAmortizationDeptVOList[
          formInfo.value.data.assetAmortizationDeptVOList.length - 1
        ].useDeptId = formInfo.value.data.useDeptId

        formInfo.value.data.assetAmortizationDeptVOList[
          formInfo.value.data.assetAmortizationDeptVOList.length - 1
        ].rate = 100
      }
      if (
        formInfo.value.data.classifyType &&
        formInfo.value.data.classifyType !== -2
      ) {
        getClassify()
      }
      formInfo.value.baseRef.clearValidate()
      formInfo.value.commonRef.clearValidate()
      formInfo.value.financeRef.clearValidate()
      if (
        formInfo.value.data.isFinanceAsset &&
        !(
          formInfo.value.data.useStatus == 1
        )
      ) {
        formInfo.value.financeInfoRules.assetAmortizationDeptVOList = [
          {
            required: true,
          },
        ]
      } else {
        formInfo.value.financeInfoRules.assetAmortizationDeptVOList = [
          {
            required: false,
          },
        ]

        if (assetAmortizationDeptTableForm.value) {
          assetAmortizationDeptTableForm.value.clearValidate()
        }
      }

      if (formInfo.value.data.depotName) {
        showFieldListItem(true, 'depotName')
        showFieldListItem(false, 'useDeptName')
      } else if (formInfo.value.data.useDeptName) {
        showFieldListItem(false, 'depotName')
        showFieldListItem(true, 'useDeptName')
      }
    }
  })
}
function getClassify() {
  getClassifyDetailsById(formInfo.value.data.classifyType).then((res) => {
    if (res && res.success) {
      formInfo.value.data.assetType =
        res.data.assetType === -2 ? '' : res.data.assetType
    }
  })
}
</script>

<style scoped>
.i-more-disabled {
  cursor: not-allowed;
}
</style>
